var mongoose = require('mongoose');
var LocalStrategy = require('passport-local').Strategy;
var crypto = require('../util/crypto');
var User = require("../models/user");
var logger = require("./logger");
var BearerStrategy = require('passport-http-bearer').Strategy;
var CONFIG = require('../config/config').Config;
var moment = require('moment');

module.exports = function(passport) {
  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.model.findOne({_id: id}, function(err, user) {
      done(err, user);
    });
  });

  // passport.use('local', new LocalStrategy({
  //   usernameField: 'username',
  //   passwordField: 'password'
  // }, function(username, password, done) {
  //   logger.info('username is', username);
  //   User.model.findOne({
  //     username: username
  //   }, function(err, user) {
  //     if (err) {
  //       logger.info(err);
  //       done(null, false, 'user not found');
  //       return;
  //     }

  //     if (!user) {
  //       done(null, false, 'user not found');
  //       return;
  //     }

  //     if (user.usertype != 'common') {
  //       done(null, false, 'not common account');
  //       return;
  //     }

  //     // successfully get the user, now verify the password
  //     if (crypto.validatePassword(password, user.password)) {
  //       // update token
  //       user.token = crypto.generateToken();
  //       user.token_created = moment().utc().format();

  //       user.save(function(err, user) {
  //         if (err) {
  //           logger.info('db error');
  //           done(null, false, 'db error');
  //           return;
  //         }

  //         done(null, user);
  //       });
  //     } else {
  //       logger.info('invalid password');
  //       done(null, false, 'invalid password');
  //     }
  //   });
  // }));

  passport.use(new BearerStrategy(
      function(token, done) {
        if (token == '') {
          return done(null, false, 'Invalid token');
        }

        User.model.findOne({
          token: token
        }, function(err, user) {
          if (err) {
            logger.debug('retrieve user from token failed ', err);
            return done(err);
          }

          if (!user) {
            logger.debug('user is null');
            return done(null, false, 'Unknown user');
          }

          // var token_created = user.token_created;
          // var passedHours = Math.abs(new Date() - token_created) / 36e5;
          // logger.debug('passed hours is ', passedHours);
          // if (passedHours > CONFIG.token_expiry_hours) {
          //   logger.debug('token expired');
          //   return done(null, false, 'Token expired');
          // }

          return done(null, user);
        });
      }
  ));
};